package com.taoding.hfhclient.HttpClient;

import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.http.HttpStatus;
import org.springframework.web.client.HttpClientErrorException;
import java.io.IOException;
import java.util.Map;

/**
 * @author liuxinghong
 * @Description: okHttp请求 回调方法  https://www.jianshu.com/p/da4a806e599b
 * @date 2019/8/30 003011:41
 */
@Slf4j
public class HttpRequest {

    /**
     * 异步get请求
     * @param url
     */
    public static void   asyncGetHttp(String url) throws Exception{
        OkHttpClient okHttpClient = new OkHttpClient();
        final Request request = new Request.Builder()
                .url(url)
                .get()//默认就是GET请求，可以不写
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                log.info("请求失败..."+e.getMessage());
                log.info("请求服务端失败： 请求信息： url"+url+"  详细信息："+request.toString());
                throw  new HttpClientErrorException(HttpStatus.BAD_REQUEST,"发起请求服务端失败");
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //处理业务逻辑
                log.info(response.code()+"---请求成功: " + response.body().string());

        }
        });
    }



    /**
     * 同步GET请求
     * @param url
     */
    public static void syncGetHttp(String url) throws Exception{
        OkHttpClient okHttpClient = new OkHttpClient();
        final Request request = new Request.Builder()
                .url(url)
                .build();
        final Call call = okHttpClient.newCall(request);
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Response response = call.execute();
                    if (HttpStatus.OK.value()==response.code()){
                        //todo: 请求成功
                        log.info("响应成功："+response.code()+"响应内容:"+response.body().string());
                        //处理业务逻辑
                    }else {
                        //请求失败
                        log.info("响应失败："+response.code()+"响应内容:"+response.body().string());
                        throw  new HttpClientErrorException(HttpStatus.INTERNAL_SERVER_ERROR,"响应失败");
                    }
                } catch (IOException e) {
                    log.info("请求服务器失败....");
                    log.info("请求参数"+"url"+url+" 详细信息："+request.toString());
                    e.printStackTrace();
                    throw  new HttpClientErrorException(HttpStatus.BAD_REQUEST,"发起请求服务端失败");
                }
            }
        }).start();
    }


    /**
     *  POST方式提交String或者json
     * @param url
     * @param body 请求体
     */
    public static void postString(String url,String body) throws Exception{
        MediaType mediaType = MediaType.parse("application/json; charset=utf-8");

        Request request = new Request.Builder()
                .url(url)
                .post(RequestBody.create(mediaType, body))
                .build();
        OkHttpClient okHttpClient = new OkHttpClient();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e)  {
                log.info("请求服务器失败...."+e.getMessage());
                log.info("请求参数："+call.request().toString());
                throw  new HttpClientErrorException(HttpStatus.BAD_REQUEST,"发起请求服务端失败");
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                log.info("请求成功："+response.protocol() + " " +response.code() + " " + response.message());
                Headers headers = response.headers();
                for (int i = 0; i < headers.size(); i++) {
                    log.info("响应头信息："+headers.name(i) + ":" + headers.value(i));
                }
                //处理业务逻辑
                log.info("响应体信息onResponse: " + response.body().string());
            }
        });
    }


    /**
     * post表单提交方式
     * @param url
     * @param form  表单
     */
    public static void  postForm(String url, Map<String,Object> form) throws Exception{
        OkHttpClient okHttpClient = new OkHttpClient();
        FormBody.Builder requestBodybuilder = new FormBody.Builder();
        form.forEach((key,value)->{
            requestBodybuilder.add(key,String.valueOf(value));
        });
        Request request = new Request.Builder()
                .url(url)
                .post(requestBodybuilder.build())
                .build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                log.info("请求服务器失败：" + e.getMessage());
                log.info("请求参数："+call.request().toString());
                throw  new HttpClientErrorException(HttpStatus.BAD_REQUEST,"发起请求服务端失败");
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //处理业务逻辑
                log.info("请求服务器成功："+response.protocol() + " " +response.code() + " " + response.message());
                Headers headers = response.headers();
                for (int i = 0; i < headers.size(); i++) {
                    log.info("响应头信息："+headers.name(i) + ":" + headers.value(i));
                }
                log.info("响应内容："+ response.body().string());
            }
        });
    }




}
